package com.colter.project.sample.thread.part03.test1;

import java.util.concurrent.Phaser;

public class Test52 {
	public static void main(String[] args) {
		Phaser phaser = new Phaser(3);
		ShowNum n1 = new ShowNum(phaser);
		ShowNum n2 = new ShowNum(phaser);
		ShowNum n3 = new ShowNum(phaser);

		Thread t1 = new Thread(n1);
		Thread t2 = new Thread(n2);
		Thread t3 = new Thread(n3);

		t1.start();
		t2.start();
		t3.start();

		try {
			t3.join();
			t2.join();
			t1.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("Completed.");

	}
}

class ShowNum implements Runnable {
	private Phaser phaser;

	public ShowNum(Phaser phaser) {
		super();
		this.phaser = phaser;
	}

	@Override
	public void run() {
		System.out.println(Thread.currentThread().getName() + " Starting!");
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName() + " 1");
		phaser.arriveAndAwaitAdvance();

		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName() + " 2");
		phaser.arriveAndAwaitAdvance();

		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName() + " 3");
		phaser.arriveAndDeregister();
	}

}
